from typing import List

from server.app.cloud_ide.schema.roles.request.role_create_request import RoleCreateRequest
from server.app.cloud_ide.schema.roles.request.role_update_request import RoleUpdateRequest
from server.app.cloud_ide.schema.roles.response.role_detail_entity import RoleDetailEntity
from server.app.cloud_ide.schema.roles.response.role_info_response import RoleInfoResponse
from server.framework.core.logger import logger
from server.framework.utils.keycloak_manager import build_keycloak_admin


class RoleService:
    def get_role_list(self, tenant_id: str) -> List[RoleDetailEntity]:
        keycloak_admin = build_keycloak_admin()
        roles = keycloak_admin.get_group(tenant_id)['subGroups']
        results = []
        for role in roles:
            role_details = keycloak_admin.get_group(role['id'])
            results.append(RoleDetailEntity(
                id=role_details['id'],
                name=role_details['name'],
                max_cpu=role_details['attributes']['max_cpu'][0],
                max_memory=role_details['attributes']['max_memory'][0],
                max_disk=role_details['attributes']['max_disk'][0],
                allow_nodes=role_details['attributes']['allow_nodes'][0]
            ))
        return results

    def get_all_roles(self, tenant_id: str):
        keycloak_admin = build_keycloak_admin()
        roles = keycloak_admin.get_group(tenant_id)['subGroups']
        return roles

    def get_role_detail_by_name(self, tenant_id: str, role_name: str):
        groups = self.get_role_list(tenant_id)
        return next((x for x in groups if x.name == role_name), None)

    def get_role_entity(self, role_id: str) -> RoleInfoResponse:
        keycloak_admin = build_keycloak_admin()
        group_details = keycloak_admin.get_group(role_id)
        entity = RoleInfoResponse(
            id=role_id,
            name=group_details['name'],
            max_cpu=group_details['attributes']['max_cpu'][0],
            max_memory=group_details['attributes']['max_memory'][0],
            max_disk=group_details['attributes']['max_disk'][0],
            allow_nodes=group_details['attributes']['allow_nodes'][0],
        )
        return entity

    def delete_roles(self, role_ids: list):
        try:
            keycloak_admin = build_keycloak_admin()
            for id in role_ids:
                keycloak_admin.delete_group(group_id=id)
            return True
        except Exception as e:
            logger.error(f'删除角色[{role_ids}]失败,异常信息:[{e}]')
            return False

    def update_role(self, data: RoleUpdateRequest):
        try:
            keycloak_admin = build_keycloak_admin()
            payload = {
                'name': data.name,
                'attributes': {
                    'max_cpu': [data.max_cpu],
                    'max_disk': [data.max_disk],
                    'allow_nodes': [data.allow_nodes],
                    'max_memory': [data.max_memory],
                }
            }
            keycloak_admin.update_group(group_id=data.id, payload=payload)
            return True
        except Exception as e:
            logger.error(f'编辑角色[{data.name}]失败,异常信息:[{e}]')
            return False

    def create_role(self, data: RoleCreateRequest):
        try:
            keycloak_admin = build_keycloak_admin()
            payload = {
                'name': data.name,
                'attributes': {
                    'max_cpu': [data.max_cpu],
                    'max_disk': [data.max_disk],
                    'allow_nodes': [data.allow_nodes],
                    'max_memory': [data.max_memory],
                }
            }
            keycloak_admin.create_group(payload=payload, parent=data.tenant_id)
            return True
        except Exception as e:
            logger.error(f'创建角色[{data.name}]失败,异常信息:[{e}]')
            return False
